<?

//	*****************************************
//	SbSE DB multiple rows insert component
//	v1.1.2 / 2012.02.15
//	*****************************************

require_once E.'_lib/_db.php';

class DB_INSERT {

	var $tables;	// into
	var $data;		// data
	var $id;		// insert id
	
	var $res;				// код ошибки	

	var $err = array (
		0 => 'success',
		1 => 'empty result',
		255 => 'not initialized'
	);
	
	function DB_INSERT() {

		$this->tables = '';
		$this->datas = '';
		$this->data = 0;
		$this->id = 0;

		$this->ai_field = 0;

		$this->db = false;

		$this->res = 255;
	}

	function init( $tables, $datas, $ai_field = 'id', $db = false ) {
	
		if ($tables)
			$this->tables = str_replace(';', '', $tables);				// ! здесь надо проверять корректность куска SQL
		else
			return 0;	// error 255 - not initialized.

		if ($datas)
			$this->datas = $datas;
		else
			return 0;	// error 255 - not initialized.
			
		if (defined('USE_ADODB'))
			if (!$db && isset($GLOBALS['db']))
				$db = $GLOBALS['db'];
		
		$this->db = $db;
		$this->ai_field = $ai_field;

//		$this->res = $this->fetch();
		$this->res = (defined('DBProto')) ? $this->fetch() : -1;

		return ! (bool) $this->res;
	}


	function storeRec($rec, $seq = false) {	// store single record with AI (by sequencer $seq) & CLOB processing
		if ($seq && !$rec[$this->ai_field])
			$rec[$this->ai_field] = $this->id = $this->db->GenID($seq);
		else
			$this->id = $rec[$this->ai_field];
			
		if (defined('USE_ADODB_OCI')) {
			$clob = array();	// get clob fields
			foreach($rec as $k => $v)
				if (is_string($v)) {
					if (strlen($v) > 4000) {
						$clob[$k] = $v;
						$rec[$k] = '';
					} else 
					if ($v == 'NULL')
						$rec[$k] = '';
				}
		}
		
		$this->db->AutoExecute($this->tables, $rec, 'INSERT');
		
		if (defined('USE_ADODB_OCI'))
			foreach($clob as $k => $v)
				$this->db->UpdateClob($this->tables, $k, $v, 'id='.$this->id);
		
		return $rec;
	}

	function fetch() {		// ! надо проверять, передали массив значений или строк - и обрабатывать соответственно.

		if (defined('USE_ADODB') && $this->db) {

			if (defined('USE_ADODB_OCI') && $this->ai_field) {
				
				if (T) {
					$temp = explode(TAS, $this->tables);
					$seq = $temp[0].'_SEQ';
				} else
					$seq =  $this->tables.'_SEQ';
			} else
				$seq = false;

			if (isset($this->datas[0])) {
	
				foreach($this->datas as $rec)
					$this->storeRec($rec, $seq);	// store multiple records
	
			} else {
	
				$this->storeRec($this->datas, $seq);	// store single record
			}
			
			if (!$seq && ($this->data = $this->db->Insert_ID()))
				$this->id = $this->data;

		} else {	// non ADODB access
	
			if (isset($this->datas[0])) {
	
				$skeys = '`'.implode("`,`", $keys = array_keys($this->datas[0])).'`';
				$v = array();
			
				foreach($this->datas as $rec) {
					$temp = array();
					foreach ($keys as $k) 
						$temp[] = ($rec[$k] == 'NULL') ? 'NULL' : "'".sql_safe($rec[$k])."'";
					$v[] = '('.implode(',', $temp).')';
				}
				$vals = implode(',', $v);
				
			} else {			
	
				$skeys = '`'.implode("`,`", array_keys($this->datas)).'`';
				
				$temp = array();
					foreach (array_values($this->datas) as $v) $temp[] = "'".sql_safe($v)."'";
				$vals = '('.implode(',', $temp).')';
			}
			
			$q = new SQL("INSERT INTO {$this->tables}
						  ($skeys)
						  VALUES $vals");
	
			$q->run();
	
			$this->id = $q->insert_id;
		}
		
		$this->data = $this->id;

		return 0;		// ok
	}
	

	function error() { return $this->err[$this->res]; }

}